load("@aspect_rules_js//js:defs.bzl", "js_binary", "js_run_binary")
load("//:build/wd_ts_project.bzl", "wd_ts_project")
load("//:build/wd_ts_test.bzl", "wd_ts_test")
load("//:build/wd_ts_type_test.bzl", "wd_ts_type_test")

wd_ts_project(
    name = "types_lib",
    srcs = glob(
        [
            "src/**/*",
            "scripts/*.ts",
        ],
        exclude = ["src/worker/**/*"],
    ),
    composite = True,
    eslintrc_json = "eslint.config.mjs",
    tsconfig_json = "//types:tsconfig.json",
    deps = [
        "//:node_modules/@types/node",
        "//:node_modules/@workerd/jsg",
        "//:node_modules/capnp-es",
        "//:node_modules/esbuild",
        "//:node_modules/prettier",
        "//:node_modules/typescript",
    ],
)

js_binary(
    name = "build_types_bin",
    data = [
        ":types_lib",
    ],
    entry_point = "scripts/build-types.js",
)

js_run_binary(
    name = "types",
    srcs = [
        "scripts/config.capnp",
        ":types_worker",
        "//:node_modules/prettier",
        "//src/workerd/server:workerd",
    ],
    out_dirs = ["definitions"],
    silent_on_success = False,  # Always enable logging for debugging
    tool = ":build_types_bin",
    visibility = ["//visibility:public"],
)

js_binary(
    name = "build_worker_bin",
    data = [
        ":types_lib",
    ],
    entry_point = "scripts/build-worker.js",
    node_options = ["--enable-source-maps"],
)

js_run_binary(
    name = "types_worker",
    srcs = [
        "//:node_modules/@workerd/jsg",
        "//:node_modules/capnp-es",
        "//:node_modules/esbuild",
        "//:node_modules/typescript",
        "//src/workerd/tools:param_extractor",
    ] + glob(
        [
            "src/**/*.ts",
            "defines/**/*.ts",
        ],
        exclude = ["src/cli/**/*"],
    ),
    outs = ["dist/index.mjs"],
    tool = ":build_worker_bin",
)

[
    wd_ts_test(
        src = src,
        composite = True,
        node_options = ["--enable-source-maps"],
        tsconfig_json = "//types:tsconfig.json",
        deps = [":types_lib"],
    )
    for src in glob(["test/**/*.spec.ts"])
]

[
    wd_ts_type_test(src = src)
    for src in glob(["test/types/**/*.ts"])
]
